package com.tanhua.dubbo.api;

import com.tanhua.model.db.Peachblossom;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

/**
 * @auther : 白月尘
 * @date : 9:12  2021/11/1
 */
@DubboService
public class PeachblossomApiIml implements PeachblossomApi{

    @Autowired
    private MongoTemplate mongoTemplate;
    //保存
    @Override
    public void saveSound(Peachblossom peachblossom) {
        mongoTemplate.save(peachblossom);
    }

    //随机接收
    @Override
    public Peachblossom recivePeachblossom(Long id) {
        Criteria criteria = Criteria.where("state").is(0).and("userId").ne(id);
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("created"))).limit(1);
        Peachblossom peachblossom = mongoTemplate.findOne(query, Peachblossom.class);
        return peachblossom;
    }

    @Override
    public void update(Peachblossom peachblossom) {
        Criteria criteria = Criteria.where("id").is(peachblossom.getId());
        Query query = Query.query(criteria);
        Update update = Update.update("state", 1);
        mongoTemplate.updateFirst(query, update, Peachblossom.class);
    }
}